// pages/food/food.js
const db = wx.cloud.database()
let searchKey = ''
Page({
    data: {
        isHiddMask: true,
        totalMoney: 0,
        totalNum: 0,
        cartList: []
    },
    onLoad: function (options) {
        searchKey = options.searchKey
        if (searchKey) {
            this.setData({
                key: searchKey
            })
            wx.setNavigationBarTitle({
                title: '搜索页',
            })
        } else {
            searchKey = ''
            wx.setNavigationBarTitle({
                title: '菜品列表页',
            })
        }
        // 获取购物车缓存数据
        let cartList = wx.getStorageSync('cart') || []
        console.log('本地缓存的购物车数据', cartList)
        this.setData({
            cartList: cartList
        })
        this.getSearchData()
    },
    getSearch(e) {
        searchKey = e.detail.value
    },
    goSearch() {
        if (searchKey && searchKey.length > 0) {
            this.getSearchData()
        } else {
            wx.showToast({
                icon: 'none',
                title: '搜索词不能为空',
            })
        }
    },
    getSearchData() {
        let cartList = this.data.cartList
        db.collection('food').where({
                name: db.RegExp({
                    regexp: searchKey,
                    options: 'i'
                })
            }).get()
            .then(res => {
                let list = res.data
                if (list && list.length > 0) {
                    list.forEach(item => {
                        if (cartList && cartList.length > 0) {
                            var result = cartList.find(cart => {
                                return cart._id == item._id
                            })
                            if (result) {
                                item.num = result.num
                            } else {
                                item.num = 0
                            }
                        } else {
                            item.num = 0
                        }
                    })
                    this.setData({
                        foodList: list
                    })
                    this.getTotal()
                }
            })
            .catch(res => {
                console.log(res)
            })
    },
    jian(e) {
        let id = e.currentTarget.dataset.id
        let list = this.data.foodList
        let cartList = this.data.cartList
        list.forEach(item => {
            if (item._id == id) {
                if (item.num > 0) {
                    item.num -= 1
                    var index = cartList.findIndex(cart => {
                        return cart._id == id
                    })
                    if (index > -1) {
                        cartList[index].num = item.num
                    }
                    if (item.num == 0) {
                        cartList.splice(index, 1)
                    }
                } else {
                    wx.showToast({
                        icon: 'none',
                        title: '数量不能小于0',
                    })
                }
            }
        })
        this.setData({
            foodList: list,
            cartList
        })
        this.getTotal()
        wx.setStorageSync('cart', cartList)
    },
    jia(e) {
        let id = e.currentTarget.dataset.id
        let list = this.data.foodList
        let cartList = this.data.cartList
        list.forEach(item => {
            if (item._id == id) {
                item.num += 1
                if (cartList && cartList.length > 0) {
                    var result = cartList.find(cart => {
                        return cart._id == id
                    })
                    if (result) {
                        result.num = item.num
                    } else {
                        cartList.push(item)
                    }
                } else {
                    cartList.push(item)
                }
            }
        })
        this.setData({
            foodList: list,
            cartList
        })
        this.getTotal()
        wx.setStorageSync('cart', cartList)
    },

    // 计算总价格和总数量
    getTotal() {
        let cartList = this.data.cartList
        let totalMoney = 0
        let totalNum = 0
        cartList.forEach(item => {
            totalNum += item.num
            totalMoney += item.num * item.price
        })
        this.setData({
            totalNum,
            totalMoney
        })
    },

    // 关闭购物车蒙层
    closeMask() {
        this.setData({
            isHiddMask: true
        })
    },
    // 打开购物车蒙层
    openMask() {
        this.setData({
            isHiddMask: false
        })
    },

    // 清空购物车
    clearCart() {
        let foodList = this.data.foodList
        foodList.forEach(item => {
            item.num = 0
        })
        this.setData({
            foodList,
            cartList: [],
            totalNum: 0,
            totalMoney: 0
        })
        wx.setStorageSync('cart', null)
    },

    // 删除购物车单条数据
    closeCartItem(e) {
        console.log(e.currentTarget.dataset.index)
        let index = e.currentTarget.dataset.index
        let cartList = this.data.cartList
        let cart = cartList[index]
        // 遍历菜品列表，把药删除的菜品的数量为0
        let foodList = this.data.foodList
        foodList.forEach(item => {
            if(cart._id == item._id){
                item.num = 0
            }
        })
        // 从购物车数组里删除当前菜品
        cartList.splice(index, 1)
        this.setData({
            foodList,
            cartList
        })
        // 重新计算总价格
        this.getTotal()
        // 把更新后的数据重新缓存
        wx.setStorageSync('cart', cartList)
    },
    goPay() {
        wx.navigateTo({
          url: '/pages/pay/pay',
        })
    }
})